package com.example.dragandview.seniorUI;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.example.dragandview.R;

public class ProcessBarActivity extends Activity {
    private TextView title;
    private ProgressBar progressBar;
    private Handler mHandler;
    private Button button;
    private int progressState = 0 ;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.seniorui_processbar);
        initView();
    }
    private void initView(){
        title = findViewById(R.id.textview_titlebar);
        title.setText("进度条");
        progressBar = findViewById(R.id.id_processbar);
        button = findViewById(R.id.btn_progressstart);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                progressStart1();
            }
        });
    }
    private void progressStart1(){
        while (progressState < 100){
            progressState += 1;
            progressBar.setProgress(progressState);
        }
    }
    private void progressStart(){
        mHandler = new Handler(){
            @Override
            public void handleMessage(@NonNull Message msg) {
                super.handleMessage(msg);
                if(msg.what == 0x111){
                    progressBar.setProgress(progressState);
                }else {
                    Toast.makeText(ProcessBarActivity.this,"耗时操作处理完成",Toast.LENGTH_SHORT).show();
                    progressBar.setVisibility(View.GONE);
                }
            }
        };
        new Thread(new Runnable() {
            @Override
            public void run() {
                while (true){
                    progressState = doWork();
                    Message m = new Message();
                    if (progressState < 100){
                        m.what = 0x111;
                        mHandler.sendMessage(m);
                    }else {
                        m.what = 0x110;
                        mHandler.sendMessage(m);
                        break;
                    }
                }
            }
            private int doWork(){
                progressState += Math.random()*10;
                try {
                    Thread.sleep(200);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                return progressState;
            }
        }).run();
    }
}
